// 音乐数据
let musicData = [];

// 播放列表数据
const playlists = {
  all: [],
  favorites: [],
  recent: [],
  // 动态创建的播放列表将存储在这里
};

// 当前播放列表和索引
let currentPlaylist = 'all';
let currentIndex = 0;
let isPlaying = false;
let isShuffle = false;
let repeatMode = 'none'; // none, one, all

// 已选择的文件夹
let selectedFolder = null;

// DOM元素引用
let elements = {};

// 初始化应用
function initApp() {
  // 获取DOM元素引用
  elements = {
    mobileMenuButton: document.getElementById('mobile-menu-button'),
    mobileMenu: document.getElementById('mobile-menu'),
    themeToggle: document.getElementById('theme-toggle'),
    header: document.getElementById('header'),
    selectFolderBtn: document.getElementById('select-folder-btn'),
    folderSelectModal: document.getElementById('folder-select-modal'),
    closeModalBtn: document.getElementById('close-modal-btn'),
    cancelSelectBtn: document.getElementById('cancel-select-btn'),
    browseFolderBtn: document.getElementById('browse-folder-btn'),
    fileInput: document.getElementById('file-input'),
    folderPath: document.getElementById('folder-path'),
    musicList: document.getElementById('music-list'),
    musicSearch: document.getElementById('music-search'),
    playPauseBtn: document.getElementById('play-pause-btn'),
    prevBtn: document.getElementById('prev-btn'),
    nextBtn: document.getElementById('next-btn'),
    shuffleBtn: document.getElementById('shuffle-btn'),
    repeatBtn: document.getElementById('repeat-btn'),
    progressBar: document.getElementById('progress-bar'),
    progressFill: document.getElementById('progress-fill'),
    progressDot: document.getElementById('progress-dot'),
    currentTime: document.getElementById('current-time'),
    totalTime: document.getElementById('total-time'),
    volumeBar: document.getElementById('volume-bar'),
    volumeFill: document.getElementById('volume-fill'),
    volumeDot: document.getElementById('volume-dot'),
    muteBtn: document.getElementById('mute-btn'),
    currentTrackTitle: document.getElementById('current-track-title'),
    currentTrackArtist: document.getElementById('current-track-artist'),
    currentTrackCover: document.getElementById('current-track-cover'),
    newPlaylistBtn: document.getElementById('new-playlist-btn'),
    newPlaylistModal: document.getElementById('new-playlist-modal'),
    closePlaylistModalBtn: document.getElementById('close-playlist-modal-btn'),
    cancelPlaylistBtn: document.getElementById('cancel-playlist-btn'),
    createPlaylistBtn: document.getElementById('create-playlist-btn'),
    playlistName: document.getElementById('playlist-name'),
    audioPlayer: document.getElementById('audio-player'),
    playlistBtn: document.getElementById('playlist-btn'),
    shufflePlayBtn: document.getElementById('shuffle-play-btn'),
    recentPlayBtn: document.getElementById('recent-play-btn'),
    emptyAddMusicBtn: document.getElementById('empty-add-music-btn'),
    fileDropArea: document.getElementById('file-drop-area'),
    confirmSelectBtn: document.getElementById('confirm-select-btn')
  };

  // 设置事件监听器
  setupEventListeners();

  // 启用音乐文件拖放
  setupMusicFileDrop();
}

// 设置事件监听器
function setupEventListeners() {
  // 导航相关
  elements.mobileMenuButton.addEventListener('click', toggleMobileMenu);
  elements.themeToggle.addEventListener('click', toggleTheme);
  window.addEventListener('scroll', handleScroll);
  
  // 文件夹选择相关
  elements.selectFolderBtn.addEventListener('click', openFolderSelectModal);
  elements.closeModalBtn.addEventListener('click', closeFolderSelectModal);
  elements.cancelSelectBtn.addEventListener('click', closeFolderSelectModal);
  elements.browseFolderBtn.addEventListener('click', openFileBrowser);
  elements.fileInput.addEventListener('change', handleFolderSelect);
  elements.folderSelectModal.addEventListener('click', closeModalOnClickOutside);
  elements.confirmSelectBtn.addEventListener('click', processSelectedFolder);
  
  // 音乐播放控制
  elements.playPauseBtn.addEventListener('click', togglePlayPause);
  elements.prevBtn.addEventListener('click', playPrevious);
  elements.nextBtn.addEventListener('click', playNext);
  elements.shuffleBtn.addEventListener('click', toggleShuffle);
  elements.repeatBtn.addEventListener('click', toggleRepeat);
  elements.progressBar.addEventListener('click', seek);
  elements.volumeBar.addEventListener('click', adjustVolume);
  elements.muteBtn.addEventListener('click', toggleMute);
  
  // 搜索功能
  elements.musicSearch.addEventListener('input', handleSearch);
  
  // 新建播放列表
  elements.newPlaylistBtn.addEventListener('click', openNewPlaylistModal);
  elements.closePlaylistModalBtn.addEventListener('click', closeNewPlaylistModal);
  elements.cancelPlaylistBtn.addEventListener('click', closeNewPlaylistModal);
  elements.createPlaylistBtn.addEventListener('click', createNewPlaylist);
  
  // 音频事件
  elements.audioPlayer.addEventListener('timeupdate', updateProgress);
  elements.audioPlayer.addEventListener('loadedmetadata', updateTotalTime);
  elements.audioPlayer.addEventListener('ended', handleTrackEnd);
  
  // 空状态下的添加音乐按钮
  elements.emptyAddMusicBtn.addEventListener('click', openFolderSelectModal);
}

// 移动端菜单切换
function toggleMobileMenu() {
  elements.mobileMenu.classList.toggle('hidden');
}

// 主题切换
function toggleTheme() {
  document.body.classList.toggle('dark');
  const icon = elements.themeToggle.querySelector('i');
  if (icon.classList.contains('fa-moon')) {
    icon.classList.remove('fa-moon');
    icon.classList.add('fa-sun');
  } else {
    icon.classList.remove('fa-sun');
    icon.classList.add('fa-moon');
  }
}

// 滚动效果
function handleScroll() {
  if (window.scrollY > 10) {
    elements.header.classList.add('shadow');
    elements.header.classList.remove('shadow-sm');
  } else {
    elements.header.classList.remove('shadow');
    elements.header.classList.add('shadow-sm');
  }
}

// 文件夹选择相关
function openFolderSelectModal() {
  elements.folderSelectModal.classList.remove('hidden');
  setupFolderDropArea();
}

function closeFolderSelectModal() {
  elements.folderSelectModal.classList.add('hidden');
}

function openFileBrowser() {
  elements.fileInput.click();
}

function handleFolderSelect(e) {
  if (e.target.files.length > 0) {
    const folder = e.target.files[0].webkitRelativePath.split('/')[0];
    elements.folderPath.textContent = folder;
    selectedFolder = e.target.files[0];
    elements.confirmSelectBtn.disabled = false;
  }
}

function closeModalOnClickOutside(e) {
  if (e.target === elements.folderSelectModal) {
    closeFolderSelectModal();
  }
}

// 设置文件夹拖放区域
function setupFolderDropArea() {
  const dropArea = document.getElementById('drop-area');
  
  ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    dropArea.addEventListener(eventName, preventDefaults, false);
  });
  
  function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
  }
  
  ['dragenter', 'dragover'].forEach(eventName => {
    dropArea.addEventListener(eventName, highlight, false);
  });
  
  ['dragleave', 'drop'].forEach(eventName => {
    dropArea.addEventListener(eventName, unhighlight, false);
  });
  
  function highlight() {
    dropArea.classList.add('border-primary');
    dropArea.classList.add('bg-primary/5');
  }
  
  function unhighlight() {
    dropArea.classList.remove('border-primary');
    dropArea.classList.remove('bg-primary/5');
  }
  
  dropArea.addEventListener('drop', handleFolderDrop, false);
}

function handleFolderDrop(e) {
  const dt = e.dataTransfer;
  const items = dt.items;
  
  if (items) {
    for (let i = 0; i < items.length; i++) {
      if (items[i].kind === 'file') {
        const entry = items[i].webkitGetAsEntry();
        if (entry && entry.isDirectory) {
          // 处理文件夹
          elements.folderPath.textContent = entry.name;
          selectedFolder = entry;
          elements.confirmSelectBtn.disabled = false;
          break;
        }
      }
    }
  }
}

// 处理选择的文件夹
function processSelectedFolder() {
  if (!selectedFolder) return;
  
  // 模拟处理文件夹内容
  elements.selectedFolder.classList.remove('hidden');
  closeFolderSelectModal();
  
  // 这里应该实现真正的文件夹扫描逻辑
  // 为了演示，我们生成一些模拟音乐数据
  const mockMusicFiles = generateMockMusicFiles(10);
  processMusicFiles(mockMusicFiles);
}

// 生成模拟音乐文件
function generateMockMusicFiles(count) {
  const mockFiles = [];
  
  for (let i = 1; i <= count; i++) {
    mockFiles.push({
      name: `歌曲 ${i}.mp3`,
      size: Math.floor(Math.random() * 10000000) + 1000000, // 1MB-10MB
      type: 'audio/mpeg',
      lastModified: Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000) // 随机30天内
    });
  }
  
  return mockFiles;
}

// 启用音乐文件拖放
function setupMusicFileDrop() {
  // 阻止默认行为
  ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    elements.fileDropArea.addEventListener(eventName, preventDefaults, false);
    document.body.addEventListener(eventName, preventDefaults, false);
  });
  
  function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
  }
  
  // 高亮效果
  ['dragenter', 'dragover'].forEach(eventName => {
    elements.fileDropArea.addEventListener(eventName, highlightDropArea, false);
  });
  
  ['dragleave', 'drop'].forEach(eventName => {
    elements.fileDropArea.addEventListener(eventName, unhighlightDropArea, false);
  });
  
  function highlightDropArea() {
    elements.fileDropArea.classList.add('border-primary');
    elements.fileDropArea.classList.add('bg-primary/5');
  }
  
  function unhighlightDropArea() {
    elements.fileDropArea.classList.remove('border-primary');
    elements.fileDropArea.classList.remove('bg-primary/5');
  }
  
  // 处理文件拖放
  elements.fileDropArea.addEventListener('drop', handleFileDrop, false);
}

function handleFileDrop(e) {
  const dt = e.dataTransfer;
  const files = dt.files;
  
  if (files.length > 0) {
    // 过滤音乐文件
    const musicFiles = Array.from(files).filter(file => {
      const ext = file.name.split('.').pop().toLowerCase();
      return ['mp3', 'wav', 'flac', 'ogg'].includes(ext);
    });
    
    if (musicFiles.length > 0) {
      processMusicFiles(musicFiles);
    } else {
      showNotification('未找到支持的音乐文件', 'error');
    }
  }
}

// 处理音乐文件
function processMusicFiles(files) {
  showNotification(`正在处理 ${files.length} 个音乐文件...`, 'info');
  
  // 为每个文件创建音乐对象
  const newMusicItems = [];
  
  files.forEach((file, index) => {
    // 模拟获取音乐元数据
    const musicItem = {
      id: Date.now() + index, // 使用时间戳生成唯一ID
      title: file.name.replace(/\.[^/.]+$/, ''), // 移除文件扩展名
      artist: '未知艺术家',
      album: '未知专辑',
      duration: '0:00',
      cover: 'https://picsum.photos/40/40?random=' + (index + 1),
      file: URL.createObjectURL(file), // 创建文件URL
      favorite: false,
      originalFile: file // 保存原始文件引用
    };
    
    newMusicItems.push(musicItem);
    
    // 异步加载音频以获取时长
    const audio = new Audio();
    audio.src = musicItem.file;
    audio.onloadedmetadata = function() {
      const duration = formatTime(audio.duration);
      musicItem.duration = duration;
      
      // 如果这是第一个处理的文件，且当前没有播放的音乐，则播放它
      if (index === 0 && musicData.length === 0) {
        musicData.push(musicItem);
        playlists.all.push(musicItem);
        updateMusicList();
        currentIndex = 0;
        setAudioSource(currentIndex);
        playMusic();
      } else {
        // 否则更新音乐列表
        updateMusicList();
      }
    };
  });
  
  // 添加到音乐数据和播放列表
  musicData = [...musicData, ...newMusicItems];
  playlists.all = [...musicData];
  
  // 更新界面
  updateMusicList();
  updatePlaylistsCount();
  
  // 启用所有功能
  enableMusicPlayerFeatures();
  
  showNotification(`成功导入 ${newMusicItems.length} 首音乐`, 'success');
}

// 启用音乐播放器功能
function enableMusicPlayerFeatures() {
  // 启用搜索框
  elements.musicSearch.disabled = false;
  
  // 启用视图切换按钮
  document.getElementById('view-grid-btn').classList.remove('opacity-50', 'cursor-not-allowed');
  document.getElementById('view-list-btn').classList.remove('opacity-50', 'cursor-not-allowed');
  
  // 启用随机播放和最近播放按钮
  elements.shufflePlayBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  elements.recentPlayBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  
  // 启用音乐播放器
  document.querySelector('footer').classList.remove('opacity-50', 'cursor-not-allowed');
}

// 音乐播放控制
function setAudioSource(index) {
  if (playlists[currentPlaylist].length === 0) return;
  
  const track = playlists[currentPlaylist][index];
  elements.audioPlayer.src = track.file;
  elements.currentTrackTitle.textContent = track.title;
  elements.currentTrackArtist.textContent = track.artist;
  elements.currentTrackCover.src = track.cover;
  
  // 更新音乐列表中的播放状态
  updatePlayingState(track.id);
  
  // 添加到最近播放
  addToRecent(track);
}

function playMusic(index = currentIndex) {
  if (playlists[currentPlaylist].length === 0) return;
  
  currentIndex = index;
  setAudioSource(currentIndex);
  elements.audioPlayer.play().then(() => {
    isPlaying = true;
    elements.playPauseBtn.innerHTML = '<i class="fa-solid fa-pause"></i>';
  }).catch(error => {
    console.error("播放失败:", error);
    showNotification('播放失败，请尝试其他文件', 'error');
  });
}

function togglePlayPause() {
  if (playlists[currentPlaylist].length === 0) return;
  
  if (isPlaying) {
    elements.audioPlayer.pause();
    isPlaying = false;
    elements.playPauseBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
  } else {
    elements.audioPlayer.play().then(() => {
      isPlaying = true;
      elements.playPauseBtn.innerHTML = '<i class="fa-solid fa-pause"></i>';
    }).catch(error => {
      console.error("播放失败:", error);
      showNotification('播放失败，请尝试其他文件', 'error');
    });
  }
}

function playPrevious() {
  if (playlists[currentPlaylist].length === 0) return;
  
  if (isShuffle) {
    currentIndex = Math.floor(Math.random() * playlists[currentPlaylist].length);
  } else {
    currentIndex = (currentIndex - 1 + playlists[currentPlaylist].length) % playlists[currentPlaylist].length;
  }
  playMusic(currentIndex);
}

function playNext() {
  if (playlists[currentPlaylist].length === 0) return;
  
  if (isShuffle) {
    currentIndex = Math.floor(Math.random() * playlists[currentPlaylist].length);
  } else {
    currentIndex = (currentIndex + 1) % playlists[currentPlaylist].length;
  }
  playMusic(currentIndex);
}

function toggleShuffle() {
  isShuffle = !isShuffle;
  elements.shuffleBtn.classList.toggle('text-primary', isShuffle);
}

function toggleRepeat() {
  if (repeatMode === 'none') {
    repeatMode = 'all';
    elements.repeatBtn.innerHTML = '<i class="fa-solid fa-repeat"></i>';
    elements.repeatBtn.classList.add('text-primary');
  } else if (repeatMode === 'all') {
    repeatMode = 'one';
    elements.repeatBtn.innerHTML = '<i class="fa-solid fa-repeat-1"></i>';
  } else {
    repeatMode = 'none';
    elements.repeatBtn.innerHTML = '<i class="fa-solid fa-repeat"></i>';
    elements.repeatBtn.classList.remove('text-primary');
  }
}

function handleTrackEnd() {
  if (repeatMode === 'one') {
    // 单曲循环
    elements.audioPlayer.currentTime = 0;
    elements.audioPlayer.play();
  } else if (repeatMode === 'all' || isShuffle) {
    // 列表循环或随机播放
    playNext();
  } else {
    // 不循环，播放停止
    isPlaying = false;
    elements.playPauseBtn.innerHTML = '<i class="fa-solid fa-play"></i>';
  }
}

// 更新进度条
function updateProgress() {
  const percent = (elements.audioPlayer.currentTime / elements.audioPlayer.duration) * 100;
  elements.progressFill.style.width = `${percent}%`;
  elements.progressDot.style.left = `${percent}%`;
  elements.currentTime.textContent = formatTime(elements.audioPlayer.currentTime);
}

// 调整进度
function seek(e) {
  if (isNaN(elements.audioPlayer.duration)) return;
  
  const progressBarRect = elements.progressBar.getBoundingClientRect();
  const clickPosition = e.clientX - progressBarRect.left;
  const percent = (clickPosition / progressBarRect.width) * 100;
  const seekTime = (percent / 100) * elements.audioPlayer.duration;
  
  elements.audioPlayer.currentTime = seekTime;
}

// 调整音量
function adjustVolume(e) {
  const volumeBarRect = elements.volumeBar.getBoundingClientRect();
  const clickPosition = e.clientX - volumeBarRect.left;
  const percent = Math.max(0, Math.min(100, (clickPosition / volumeBarRect.width) * 100));
  
  elements.audioPlayer.volume = percent / 100;
  elements.volumeFill.style.width = `${percent}%`;
  elements.volumeDot.style.left = `${percent}%`;
  
  // 更新静音图标
  if (elements.audioPlayer.volume === 0) {
    elements.muteBtn.innerHTML = '<i class="fa-solid fa-volume-off"></i>';
  } else if (elements.audioPlayer.volume < 0.5) {
    elements.muteBtn.innerHTML = '<i class="fa-solid fa-volume-down"></i>';
  } else {
    elements.muteBtn.innerHTML = '<i class="fa-solid fa-volume-up"></i>';
  }
}

// 切换静音
function toggleMute() {
  if (elements.audioPlayer.volume > 0) {
    elements.audioPlayer.dataset.volume = elements.audioPlayer.volume;
    elements.audioPlayer.volume = 0;
    elements.volumeFill.style.width = '0%';
    elements.volumeDot.style.left = '0%';
    elements.muteBtn.innerHTML = '<i class="fa-solid fa-volume-off"></i>';
  } else {
    const volume = parseFloat(elements.audioPlayer.dataset.volume) || 0.7;
    elements.audioPlayer.volume = volume;
    elements.volumeFill.style.width = `${volume * 100}%`;
    elements.volumeDot.style.left = `${volume * 100}%`;
    
    if (volume < 0.5) {
      elements.muteBtn.innerHTML = '<i class="fa-solid fa-volume-down"></i>';
    } else {
      elements.muteBtn.innerHTML = '<i class="fa-solid fa-volume-up"></i>';
    }
  }
}

// 更新总时长
function updateTotalTime() {
  elements.totalTime.textContent = formatTime(elements.audioPlayer.duration);
}

// 格式化时间
function formatTime(seconds) {
  if (isNaN(seconds)) return '0:00';
  
  const minutes = Math.floor(seconds / 60);
  seconds = Math.floor(seconds % 60);
  
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}

// 更新音乐列表
function updateMusicList() {
  if (musicData.length === 0) {
    elements.musicList.innerHTML = `
      <tr>
        <td colspan="6" class="py-12 text-center">
          <div class="flex flex-col items-center">
            <div class="w-16 h-16 bg-neutral-100 rounded-full flex items-center justify-center mb-4">
              <i class="fa-solid fa-music text-2xl text-neutral-400"></i>
            </div>
            <h3 class="text-lg font-medium text-neutral-700 mb-1">暂无音乐文件</h3>
            <p class="text-neutral-500 mb-4">请选择本地音乐目录或拖放音乐文件到此处</p>
            <button id="empty-add-music-btn" class="py-2 px-4 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-all flex items-center space-x-2">
              <i class="fa-solid fa-plus"></i>
              <span>添加音乐</span>
            </button>
          </div>
        </td>
      </tr>
    `;
    return;
  }
  
  elements.musicList.innerHTML = '';
  
  playlists[currentPlaylist].forEach((music, index) => {
    const isPlaying = index === currentIndex && elements.audioPlayer.paused === false;
    const favoriteIcon = music.favorite ? 
      '<i class="fa-solid fa-heart text-primary"></i>' : 
      '<i class="fa-regular fa-heart"></i>';
    
    const row = document.createElement('tr');
    row.className = `border-b border-neutral-100 hover:bg-neutral-50 transition-colors music-item ${isPlaying ? 'bg-primary/5' : ''}`;
    row.dataset.id = music.id;
    
    row.innerHTML = `
      <td class="py-3">
        <input type="checkbox" class="rounded text-primary focus:ring-primary">
      </td>
      <td class="py-3">
        <div class="flex items-center space-x-3">
          <img src="${music.cover}" alt="${music.title}" class="w-10 h-10 rounded object-cover">
          <div>
            <div class="font-medium ${isPlaying ? 'text-primary' : ''}">${music.title}</div>
            <div class="text-xs text-neutral-500 hidden sm:block">${music.artist}</div>
          </div>
          ${isPlaying ? 
            '<div class="ml-2 music-visualizer"><span></span><span></span><span></span><span></span><span></span></div>' : 
            ''}
        </div>
      </td>
      <td class="py-3 hidden md:table-cell">${music.artist}</td>
      <td class="py-3 hidden sm:table-cell">${music.album}</td>
      <td class="py-3 hidden lg:table-cell">${music.duration}</td>
      <td class="py-3 text-right">
        <div class="flex items-center justify-end space-x-2">
          <button class="p-2 rounded-full hover:bg-neutral-100 transition-colors add-to-favorites-btn">
            ${favoriteIcon}
          </button>
          <button class="p-2 rounded-full hover:bg-neutral-100 text-neutral-600 transition-colors">
            <i class="fa-solid fa-ellipsis-h"></i>
          </button>
        </div>
      </td>
    `;
    
    elements.musicList.appendChild(row);
    
    // 添加事件监听器
    row.addEventListener('click', (e) => {
      if (!e.target.closest('button') && !e.target.closest('input')) {
        playMusic(index);
      }
    });
    
    // 收藏按钮
    const favoriteBtn = row.querySelector('.add-to-favorites-btn');
    favoriteBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      toggleFavorite(music.id);
    });
  });
}

// 更新播放状态
function updatePlayingState(trackId) {
  const musicItems = document.querySelectorAll('.music-item');
  
  musicItems.forEach(item => {
    if (item.dataset.id == trackId) {
      item.classList.add('bg-primary/5');
      const titleElement = item.querySelector('.font-medium');
      titleElement.classList.add('text-primary');
    } else {
      item.classList.remove('bg-primary/5');
      const titleElement = item.querySelector('.font-medium');
      titleElement.classList.remove('text-primary');
    }
  });
}

// 切换收藏状态
function toggleFavorite(musicId) {
  const music = musicData.find(item => item.id == musicId);
  
  if (music) {
    music.favorite = !music.favorite;
    
    // 更新收藏列表
    if (music.favorite) {
      if (!playlists.favorites.some(item => item.id == musicId)) {
        playlists.favorites.push(music);
      }
    } else {
      playlists.favorites = playlists.favorites.filter(item => item.id != musicId);
    }
    
    // 更新收藏按钮图标
    const favoriteBtn = document.querySelector(`.music-item[data-id="${musicId}"] .add-to-favorites-btn`);
    if (favoriteBtn) {
      favoriteBtn.innerHTML = music.favorite ? 
        '<i class="fa-solid fa-heart text-primary"></i>' : 
        '<i class="fa-regular fa-heart"></i>';
    }
    
    // 更新播放列表计数
    updatePlaylistsCount();
    
    // 显示通知
    showNotification(music.favorite ? '已添加到喜欢的音乐' : '已从喜欢的音乐中移除', 'success');
  }
}

// 添加到最近播放
function addToRecent(track) {
  // 检查是否已在最近播放列表中
  const index = playlists.recent.findIndex(item => item.id === track.id);
  
  if (index !== -1) {
    // 如果已存在，则移到最前面
    playlists.recent.splice(index, 1);
  }
  
  // 添加到最前面
  playlists.recent.unshift(track);
  
  // 限制列表长度为10
  if (playlists.recent.length > 10) {
    playlists.recent.pop();
  }
  
  // 更新播放列表计数
  updatePlaylistsCount();
}

// 更新播放列表计数
function updatePlaylistsCount() {
  document.querySelector('.playlist-item[data-playlist="all"] span:last-child').textContent = playlists.all.length;
  document.querySelector('.playlist-item[data-playlist="favorites"] span:last-child').textContent = playlists.favorites.length;
  document.querySelector('.playlist-item[data-playlist="recent"] span:last-child').textContent = playlists.recent.length;
}

// 搜索功能
function handleSearch() {
  const searchTerm = elements.musicSearch.value.toLowerCase().trim();
  
  if (!searchTerm) {
    // 如果搜索框为空，则显示所有音乐
    playlists[currentPlaylist] = [...musicData];
    updateMusicList();
    return;
  }
  
  // 过滤音乐
  playlists[currentPlaylist] = musicData.filter(music => {
    return music.title.toLowerCase().includes(searchTerm) || 
           music.artist.toLowerCase().includes(searchTerm) || 
           music.album.toLowerCase().includes(searchTerm);
  });
  
  updateMusicList();
}

// 新建播放列表
function openNewPlaylistModal() {
  elements.newPlaylistModal.classList.remove('hidden');
  elements.playlistName.focus();
}

function closeNewPlaylistModal() {
  elements.newPlaylistModal.classList.add('hidden');
  elements.playlistName.value = '';
}

function createNewPlaylist() {
  const name = elements.playlistName.value.trim();
  
  if (!name) {
    showNotification('播放列表名称不能为空', 'error');
    return;
  }
  
  // 检查是否已存在同名播放列表
  if (playlists[name]) {
    showNotification('已存在同名的播放列表', 'error');
    return;
  }
  
  // 创建新播放列表
  playlists[name] = [];
  
  // 更新UI
  const playlistContainer = document.querySelector('.playlist-item').parentNode;
  const newPlaylist = document.createElement('div');
  newPlaylist.className = 'flex items-center justify-between playlist-item cursor-pointer';
  newPlaylist.dataset.playlist = name;
  
  newPlaylist.innerHTML = `
    <div class="flex items-center space-x-2">
      <div class="w-8 h-8 rounded bg-neutral-100 flex items-center justify-center text-neutral-600">
        <i class="fa-solid fa-music text-sm"></i>
      </div>
      <span class="font-medium text-sm">${name}</span>
    </div>
    <span class="text-xs text-neutral-500">0</span>
  `;
  
  // 插入到"新建播放列表"按钮之前
  playlistContainer.insertBefore(newPlaylist, elements.newPlaylistBtn.parentNode);
  
  // 添加点击事件
  newPlaylist.addEventListener('click', function() {
    currentPlaylist = name;
    updateMusicList();
  });
  
  // 关闭对话框
  closeNewPlaylistModal();
  
  // 显示通知
  showNotification(`成功创建播放列表"${name}"`, 'success');
}

// 显示通知
function showNotification(message, type = 'info') {
  // 创建通知元素
  const notification = document.createElement('div');
  notification.className = `fixed top-4 right-4 px-4 py-2 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-y-[-20px] opacity-0 ${
    type === 'success' ? 'bg-green-500 text-white' : 
    type === 'error' ? 'bg-red-500 text-white' : 
    'bg-blue-500 text-white'
  }`;
  
  notification.textContent = message;
  
  // 添加到页面
  document.body.appendChild(notification);
  
  // 触发动画
  setTimeout(() => {
    notification.classList.remove('translate-y-[-20px]', 'opacity-0');
  }, 10);
  
  // 3秒后移除
  setTimeout(() => {
    notification.classList.add('translate-y-[-20px]', 'opacity-0');
    setTimeout(() => {
      document.body.removeChild(notification);
    }, 300);
  }, 3000);
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);  